#!/usr/bin/python
# Filename:altman.py


from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage
import sys,os

ACTION_DOWN = 1
ACTION_UP = 0
ACTION_MOVE = 2

file_handle = None

#log_content = ""
download_log_command = "adb pull /sdcard/altman.log ."

#sets a variable with the package's internal
package = 'com.taobao.taobao'

#set a variable with the name of an Activity
mainActivity = 'com.taobao.tao.Welcome'

#set the name of the component to start
runComponent = 'com.taobao.taobao/com.taobao.tao.Welcome'

log_content = ""

#Load touch locus log file , and parse user motion event 
def load_touch_locus():
    global log_content


    log_content = str(log_content)
    json_content = eval(log_content)
  
    count = str(len(json_content))
    print "...convert json object success,have "+count+" records..."
    print "....start parse log file...."
    
    index = 1
    i=0
    is_move = False
    move_start_point_x = 0
    move_start_point_y = 0
    move_finish_point_x = 0
    move_finish_point_y = 0

    drag_time = 0
    
    for line in json_content:
        print "sleep"+str(abs(line['sleep_time']))
        MonkeyRunner.sleep(abs(line['sleep_time']))

        # type:0 touch event, 1 key event
        if line['type'] == 0:
            # touch down event:ACTION_DOWN
            if line['action'] == 0 and json_content[int(i+1)]['action'] !=2:
                action = "DOWN"
                device.touch(line['point']['x'],line['point']['y'],action)
                print "down:"+str(line)
            # touch up event: ACTION_UP
            if line['action'] == 1 and json_content[int(i-1)]['action'] !=2:
                device.touch(line['point']['x'],line['point']['y'],'UP')
                print "up:"+str(line)
            # touch move event:ACTION_MOVE
            if line['action'] == 2:
                drag_time = drag_time+float(line['sleep_time'])
                if not is_move:
                    move_start_point_x = line['point']['start_point']['x']
                    move_start_point_y = line['point']['start_point']['y']
                    is_move = True

                print "next action:"+str(json_content[int(i+1)]['action'])+"|"+str(i)
                
                if json_content[int(i+1)]['action'] !=2:
                    is_move = False
                    device.drag((move_start_point_x,move_start_point_y),(line['point']['end_point']['x'],line['point']['end_point']['y']),drag_time,10)
                    print "drag:"+"start x:"+str(move_start_point_x)+"|y:"+str(move_start_point_y)+str(line)
                    MonkeyRunner.sleep(1)
                    drag_time =0
        if line['type'] == 1:
            print line
            if line['key_code'] == 4:
                device.press("KEYCODE_BACK","DOWN")
            if line['key_code'] == 82:
                device.press("KEYCODE_MENU","DOWN")
            MonkeyRunner.sleep(1)
#        if line['type'] == 2:
#            print line
#            result = device.takeSnapshot()
#            result.writeToFile("./snapshot/taobao_snapshot_"+str(index),"png")
#            MonkeyRunner.sleep(5)
#            index +=1
        i +=1

def download_touch_log():
    print "start download touch log file..."
    result = os.popen(download_log_command)
    print result
    print "downlaod success"
    open_touch_log()
    
def open_touch_log():
    print "start open log file.."
    #TODO: get locus log from debug devices by adb tool,not static file log
    global file_handle
    try:
        file_handle = open('Altman.log','r')
        global log_content
        log_content= file_handle.read()
        log_content = "["+str(log_content)+"]"
    except IOError:
        print "not found local touch log file,start download from mobile devices by adb tools..."
        return False
    finally:
        file_handle.close()
        
  
    print "success open log file"
    return True

    
def main():
    global device
    
    print "waiting for connecion...."
    device = MonkeyRunner.waitForConnection()

    if not open_touch_log():
        download_touch_log()
    
    print "installing apk......"

    device.installPackage('./taobaoTrunk.apk')
    
    device.startActivity(component=runComponent)
    MonkeyRunner.sleep(10)

    if not os.path.exists("./snapshot/"):
        os.mkdir("./snapshot/")
    load_touch_locus();

    result = device.takeSnapshot()

    result.writeToFile('./shot_lastest.png','png')    
    
if __name__ == '__main__':
     main()        
        
